// controllers/paymentController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 模拟支付
const createPayment = async (req, res) => {
  const { order_id, payment_method } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 获取订单
    const [orders] = await connection.execute('SELECT * FROM orders WHERE id = ? AND status = 0', [order_id]);
    if (orders.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '订单未找到或已支付');
    }
    const order = orders[0];
    const amount = order.total_amount;

    // 模拟支付成功
    const transaction_no = 'TXN' + Date.now();
    const paid_at = new Date();

    // 插入支付记录
    const [paymentResult] = await connection.execute(
      'INSERT INTO payments (order_id, amount, payment_method, status, transaction_no, paid_at) VALUES (?, ?, ?, ?, ?, ?)',
      [order_id, amount, payment_method || 0, 1, transaction_no, paid_at]
    );

    // 更新订单状态为已支付
    await connection.execute('UPDATE orders SET status = 3 WHERE id = ?', [order_id]);

    await connection.commit();
    sendResponse(res, 200, '支付成功', { transaction_no });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '支付失败', error.message);
  } finally {
    connection.release();
  }
};
// 获取所有的字符记录
const getPayments =async (req, res)=>{
  const { page = 1, pageSize = 10 } = req.query;
  const offset = (page - 1) * pageSize;
  const [rows] = await pool.execute(`
    SELECT p.*, o.order_no 
    FROM payments p 
    LEFT JOIN orders o ON p.order_id = o.id 
    ORDER BY p.paid_at DESC
    LIMIT ? OFFSET ?
  `, [pageSize, offset]);
  sendResponse(res, 200, '获取支付记录成功', rows);
}

// 获取支付记录详情
const getPaymentById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute(`
      SELECT p.*, o.order_no 
      FROM payments p 
      LEFT JOIN orders o ON p.order_id = o.id 
      WHERE p.id = ?
    `, [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '支付记录未找到');
    }
    sendResponse(res, 200, '获取支付记录成功', rows[0]);  
  } catch (error) {
    sendResponse(res, 500, '获取支付记录失败', error.message);
  }
};

module.exports = {
  createPayment,
  getPayments,
  getPaymentById
};